﻿using Ldt.DataEngine.RuleAssemble;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.DateAssemble;
using LdtJudge.DataEngine.Common.MoneyAssemble;
using LdtJudge.DataEngine.Common.StringAssemble;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace LdtJudge.DataEngine.Common.ElementConvertFormat
{
    /// <summary>
    /// 要素转化通用函数集合，将函数配置到配置文件中，之后通过反射执行函数
    /// 为了配置方便将函数名都改成小写格式
    /// </summary>
    public static class ElementConvertCommonFun
    {
        private static string connstr = "Ldt_JudgeDocSystem";

        /// <summary>
        /// 获取审判机关编号
        /// </summary>
        /// <param name="nameValue">审判机关名称</param>
        /// <param name="casetypeid">案件类型</param>
        /// <returns>审判机关编号</returns>
        public static string getcourtidbyname(string nameValue,string casetypeid,string sql="")
        {
            if (nameValue.Equals("人民法院"))
            {//20180411 修改前置分析，如果文书中的法院是人民法院，则不进行转法院ID
                return null;
            }
            string province = RuleParseClass.GetParseValue("CourtIDSplitA1", nameValue);
            string city = RuleParseClass.GetParseValue("CourtIDSplitA2", nameValue);
            string town = RuleParseClass.GetParseValue("CourtIDSplitA3", nameValue);
            string postStr = RuleParseClass.GetParseValue("CourtIDSplitA4", nameValue);

            StringBuilder strSQL = new StringBuilder();
            //strSQL.Append("select courtID,CH_Name from sys_Court where (1=1)");
            strSQL.Append(" (1=1) ");
            if (province != string.Empty) strSQL.Append("and (ch_Province='" + province + "')");
            if (city != string.Empty) strSQL.Append("and (ch_City='" + city + "' or ch_Province='" + city + "')");
            if (town != string.Empty) strSQL.Append("and (ch_CountyAndDistrict='" + town + "')");
            if (postStr != string.Empty) strSQL.Append("and (CH_Suffix='" + postStr + "')");

            Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon(connstr);
            var obj = sqlSyscom.GetDataTableCourt(strSQL.ToString());
            if (obj.Count>0)
                return obj[0].CourtID.ToString();
            else
            {
                //加入法院模糊匹配
                string sqlstr = " CH_ShortName like '%" + nameValue + "%'";
                var obje = sqlSyscom.GetDataTableCourt(sqlstr);
                if (obje.Count > 0)
                    return obje[0].CourtID.ToString();
            }
            return "";
        }
        /// <summary>
        /// 获取监狱机关编号
        /// </summary>
        /// <param name="nameValue">审判机关名称</param>
        /// <param name="casetypeid">案件类型</param>
        /// <returns>审判机关编号</returns>
        public static string getprisonbyname(string nameValue, string casetypeid, string sql = "")
        {
            return InsideMethodSql(nameValue, sql);
        }
        /// <summary>
        /// 行政机关名称获取ID
        /// </summary>
        /// <param name="nameValue"></param>
        /// <param name="casetypeid"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static string getmarketsupervision(string nameValue, string casetypeid, string sql = "")
        {
            Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon(connstr);
            return sqlSyscom.GetMarketSupervision(nameValue);
        }
        /// <summary>
        /// 政执法领域获取ID
        /// </summary>
        /// <param name="nameValue"></param>
        /// <param name="casetypeid"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static string getenforcementid(string nameValue, string casetypeid, string sql = "") 
        {
            Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon(connstr);
            return sqlSyscom.GetMarketSupervisionCaseid(nameValue);
        }
        /// <summary>
        /// 获取公安机关编号
        /// </summary>
        /// <param name="nameValue">审判机关名称</param>
        /// <param name="casetypeid">案件类型</param>
        /// <returns>审判机关编号</returns>
        public static string getpublicsecuritybyname(string nameValue, string casetypeid, string sql = "")
        {
            return InsideMethodSql(nameValue, sql);
        }
        /// <summary>
        /// 根据检察机关名称获取其ID
        /// </summary>
        /// <param name="nameValue">检察机关名称</param>
        /// <param name="casetypeid">案件类型</param>
        /// <returns></returns>
        public static string getprocuratorateidbyname(string nameValue, string casetypeid, string sql = "")
        {
            // 通过正则获取省市区镇信息
            string province = RuleParseClass.GetParseValue("CourtIDSplitA1", nameValue);
            string city = RuleParseClass.GetParseValue("CourtIDSplitA2", nameValue);
            string town = RuleParseClass.GetParseValue("CourtIDSplitA3", nameValue);
            string postStr = RuleParseClass.GetParseValue("CourtIDSplitA4", nameValue);

            // 精确查找
            StringBuilder strSQL = new StringBuilder();
            strSQL.Append(" (1=1) ");
            if (province != string.Empty) strSQL.Append("and (PD_Province='" + province + "')");
            if (city != string.Empty) strSQL.Append("and (PD_City='" + city + "' or PD_Province='" + city + "')");
            if (town != string.Empty) strSQL.Append("and (PD_CountyAndDistrict='" + town + "')");
            if (postStr != string.Empty) strSQL.Append("and (PD_Suffix='" + postStr + "')");

            Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon(connstr);
            var obj = sqlSyscom.GetDataTableSys_prosecutordept(strSQL.ToString());
            if (obj != null && obj.Count>0)
                return obj[0].PD_ID.ToString();
            else
            {
                // 模糊匹配
                string sqlstr = " PD_ShortName like '%" + nameValue + "%'";
                var obje = sqlSyscom.GetDataTableSys_prosecutordept(sqlstr);
                if (obje != null && obj.Count > 0)
                    return obje[0].PD_ID.ToString();
            }
            return "";
        }
        /// <summary>
        /// 根据案件名称转换为案件Code
        /// </summary>
        /// <param name="nameValue">值内容</param>
        /// <param name="casetypeid">案件类型</param>
        /// <param name="sql">执行的SQL语句</param>
        /// <returns></returns>
        public static string getcasetypebyname(string nameValue, string casetypeid, string sql = "")
        {
            return InsideMethodSql(nameValue, sql);
        }
        /// <summary>
        /// 根据案由名称转换为案由Code
        /// </summary>
        /// <param name="nameValue">值内容</param>
        /// <param name="casetypeid">案件类型</param>
        /// <param name="sql">执行的SQL语句</param>
        /// <returns></returns>
        public static string getcasecausebyname(string nameValue, string casetypeid, string sql = "")
        {
            var ccid = string.Empty;
            Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon(connstr);
            //加入一个案件ID转换机制；
            string casetypeidNew=sqlSyscom.GetCaseTypeID(casetypeid);
            var cause = sqlSyscom.GetCauseByName(nameValue, casetypeidNew);
            if(cause!=null)
            {
                if(cause.CC_NodeType==2)
                {
                    ccid = cause.CC_ID;
                }
                else
                {
                    var allParentId = cause.AllParentId;
                    if(!string.IsNullOrWhiteSpace(allParentId))
                    {
                        var parentIdList = allParentId.Split(',').Reverse().ToList();

                        foreach (var id in parentIdList)
                        {
                            var currentCause = sqlSyscom.GetCauseById(id.Trim());
                            if (currentCause.CC_NodeType == 2)
                            {
                                ccid = currentCause.CC_ID;
                                break;
                            }
                        }
                    }
                }
            }
            return ccid;
        }
        /// <summary>
        /// 根据SQL语句进行获取对应字段内容值；
        /// </summary>
        /// <param name="nameValue">值内容</param> 
        /// <param name="sql">执行的SQL语句</param>
        /// <returns></returns>
        private static string InsideMethodSql(string nameValue, string sql) 
        {
            if (!string.IsNullOrWhiteSpace(sql))
            {
                Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon(connstr);
                DataTable oTb = sqlSyscom.GetDataTable(sql);
                if (oTb != null && oTb.Rows.Count > 0)
                {
                    string columnName = oTb.Columns[1].ColumnName;
                    DataRow[] finalArr = oTb.Select(columnName + "='" + nameValue + "'");

                    if (finalArr.Length > 0)
                        return LdFormat.ObjectToString(finalArr[0][0]);
                }
            }
            return string.Empty;
        }
        /// <summary>
        /// 时间格式转化
        /// </summary>
        /// <param name="orgValue">时间内容</param>
        /// <param name="formatType">需要转化的格式</param>
        /// <returns></returns>
        public static string convertdatetime(string orgValue, string casetypeid,string formatType)
        {
            string re = string.Empty;
            switch (formatType.ToLower())
            {
                //时间格式转换 天，日
                case "datetime":
                    Match dateMatch = Regex.Match(orgValue, @"[\d零O一二三四五六七八九十]{1,4}年[\d零O一二三四五六七八九十]{1,3}月[\d零O一二三四五六七八九十]{1,3}日(?=.*?" + orgValue + ")");
                    string relatDateStr = dateMatch.Value;      //关联的日期值
                    re = LdFormat.FormatDateCompute(relatDateStr, orgValue);
                    break;
                //转中文日期
                case "chinesedate":
                    re = ConvertStingToDateTime.ConvertToDate(orgValue);
                    break;
                //转换标准时间
                case "standarddate":
                    re = ConvertStingToDateTime.ConvertToStandardDate(orgValue);
                    break;
                case "shortdate"://短时间
                    re = ConvertStingToDateTime.ConvertToShortDate(orgValue);
                    break;
                default:
                    re = LdFormat.FormatDataField(formatType, orgValue);
                    break;
            }
            return re;
        }

        /// <summary>
        /// 转化金额
        /// </summary>
        /// <param name="orgvalue">原始值</param>
        /// <returns></returns>
        public static string convertmoney(string orgvalue, string casetypeid,string sql = "")
        {
            string re = string.Empty;
            AmountConvert amountConvert = new AmountConvert();
            re = amountConvert.DataConvertNumber(orgvalue,false);
            
            return re; 
        }

        /// <summary>
        /// 根据银行名称获取银行ID
        /// </summary>
        public static string getbankidbyname(string nameValue,string casetypeid,string sql="")
        {
            Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon(connstr);
            return sqlSyscom.GetSYS_BankIdByName(nameValue);
        }

        /// <summary>
        /// 刑期转换函数
        /// </summary>
        public static string sentencetransform(string orgvalue)
        {
            string result = orgvalue;
            if (!string.IsNullOrWhiteSpace(orgvalue))
            {
                if (Regex.IsMatch(orgvalue, "年|月"))
                {
                    double nYear = MoneyAssemble.LdtMoneyFormat.DecodeNumberCn(Regex.Match(orgvalue, @"[零一二三四五六七八九十\d]*(?=年)").Value);
                    double nMonth = MoneyAssemble.LdtMoneyFormat.DecodeNumberCn(Regex.Match(orgvalue, @"[零一二三四五六七八九十\d]*(?=个?月)").Value);
                    double nDay = MoneyAssemble.LdtMoneyFormat.DecodeNumberCn(Regex.Match(orgvalue, @"[零一二三四五六七八九十\d]*(?=日|天)").Value);

                    result = (nYear * 365 + nMonth * 30 + nDay).ToString();
                }
            }
            return result;
        }

        /// <summary>
        /// 中文大写数字转阿拉伯小写数字
        /// </summary>
        /// <param name="orgvalue"></param>
        /// <returns></returns>
        public static string numbertolower(string nameValue, string casetypeid, string sql = "")
        {
            string re = string.Empty;
            AmountConvert amountConvert = new AmountConvert();
            re = amountConvert.DataConvertNumber(nameValue, false);
            return re;
        }

        /// <summary>
        /// 公共机构名称转公共机构ID
        /// </summary>
        public static string getorganizationidbyname(string nameValue, string casetypeid, string sql = "")
        {
            Data.SqlSysCommon sqlSyscom = new Data.SqlSysCommon(connstr);
            return sqlSyscom.GetOrganizationIdByName(nameValue);
        }

        /// <summary>
        /// 日期计算
        /// </summary>
        public static string datecompute(string nameValue,string casetypeid,string sql="")
        {
            string result = string.Empty;
            if(!string.IsNullOrWhiteSpace(nameValue))
            {
                result = nameValue;
                var ruleResult= RuleParseClass.GetParseRegCodeValueManyOrg("EI2312251647240001", new List<string> { nameValue });
                if(ruleResult!=null && ruleResult.Count>0)
                {
                    string dateVaule = ruleResult[0];
                    string operationValue = string.Empty;
                    if (ruleResult.Count > 1)
                        operationValue = ruleResult[1];
                    if (!string.IsNullOrWhiteSpace(operationValue))
                    {
                        if (!string.IsNullOrWhiteSpace(dateVaule))
                        {
                            DateTime oRelatTime = DateTime.Parse(dateVaule);
                            switch (operationValue)
                            {
                                case "当日":
                                case "同日":
                                    return oRelatTime.ToString("yyyy年MM月dd日");
                                case "次日":
                                case "第二天":
                                case "第2天":
                                    return oRelatTime.AddDays(1).ToString("yyyy年MM月dd日");
                            }
                        }
                    }
                    else
                        result = dateVaule;
                }
            }
            return result;
        }
    }
}
